<?php
/**
 * Created by PhpStorm.
 * User: yiyu
 * Email: smalleasyu@gmail.com
 * Date: 2020-01-21 23:03:53
 * Desc: 微信小程序消息处理service
 * Link: 参考https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/customer-message/receive.html
 */

namespace app\base\service\WeChat;

use app\base\service\BaseService;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Transfer;
use app\core\log\Log4dd;
use app\core\exception\BusinessException;

class MiniProgramMessageHandlerService extends BaseService
{

    protected $ToUserName; // 接收方帐号（该公众号 ID）
    protected $FromUserName; // 发送方帐号（OpenID, 代表用户的唯一标识）
    protected $CreateTime; // 消息创建时间（时间戳）
    protected $MsgId; // 消息 ID（64位整型）
    protected $MsgType;// 消息 类型

    public static function AutoReply($appId = '')
    {
        try {
            $app = Factory::miniProgram(WeChatBaseService::instance()->getConfigByAppId($appId, 'mini_program'));
            $app->server->push(function($message) use ($app){
                Log4dd::info('小程序客服解密原始消息', $message);
                return new Transfer();
                switch ($message['MsgType']) {
                    case 'text':
                        $new_message = self::textMessageHandler($message['Content']);
                        break;
                    case 'image':
                        $new_message = self::imageMessageHandler($message['mediaId'], $message['PicUrl']);
                        break;
                    case 'miniprogrampage'://小程序卡片消息
                        $new_message = self::miniProgramPageMessageHandler($message['Title'], $message['AppId'], $message['PagePath'],
                            $message['ThumbUrl'], $message['ThumbMediaId']);
                        break;
                    case 'event':
                        $new_message = self::eventMessageHandler($message['Event'], $message['SessionFrom']);
                        break;
                    default:
                        $new_message = self::textMessageHandler();
                        break;
                }

                $app->customer_service->message($new_message)->to($message['FromUserName'])->send();
            });

            $response = $app->server->serve();
            return $response->send();
        } catch (BusinessException $e) {
            Log4dd::error('微信小程序客服消息发送失败:' . $e->getMessage(), func_get_args(), $e);
        }
    }

    /**
     * Desc:
     * Date: 2020/1/22 0:25
     * Author: yiyu
     * @param string $content 文本消息内容
     * @return object
     */
    private static function textMessageHandler($content = '')
    {
        switch ($content) {
            case 1:
                return SendMessage::instance()->sendTextMsg('您发送了数字1');
                break;
            case 2:
                return SendMessage::instance()->sendTextMsg('您发送了数字2');
                break;
            default:
                //return SendMessage::instance()->sendTextMsg('嗨~亲爱的圈友你好，已为你连线客服小妹，请问有什么问题呢？');
                break;
        }

    }


    /**
     * Desc:
     * Date: 2020/1/22 0:32
     * Author: yiyu
     * @param string $mediaId 图片消息媒体id，可以调用多媒体文件下载接口拉取数据
     * @param string $picUrl 图片链接
     * @return object
     */
    private static function imageMessageHandler($mediaId, $picUrl)
    {
        return SendMessage::instance()->sendTextMsg('我们已经收到了您发送的卡片消息');
    }

    private static function miniProgramPageMessageHandler($title, $appId, $pagePath, $thumbUrl, $thumbMediaId)
    {
        return SendMessage::instance()->sendTextMsg('我们已经收到了您发送的图片消息');
    }

    private static function eventMessageHandler($event, $sessionFrom = '')
    {
        return SendMessage::instance()->sendTextMsg('嗨~亲爱的圈友你好，已为你连线客服小妹，请问有什么问题呢？');
    }

}